# coding=utf-8

import time
import sys
import logging
from flask import Flask, g, session
from flask_login import LoginManager
from flask_mail import Mail
from redis import Redis

# from flask_session import Session


app = Flask(__name__)
app.config.from_object('over.settings')

mail = Mail(app)

redis = Redis()
app.redis = redis

# sess = Session()
# sess.init_app(app)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "over.handlers.auth.login"

FORMAT = "%(asctime)-15s  %(message)s"

logging.basicConfig(filename='error.log', level=logging.DEBUG)
logger = logging.getLogger()
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(FORMAT))
app.logger.addHandler(handler)
logger.addHandler(handler)


@login_manager.user_loader
def load_user(user_id):
    from .model import User

    user = User.query.get(user_id)
    g.user = user
    return user


@app.context_processor
def context_processor():
    return {
        'site_title': app.config['SITE_TITLE'],
        'product_name': app.config['SITE_TITLE'],
        'site_name': app.config['SITE_NAME'],
        'month_price': app.config['MONTH_PRICE'],
        'year_price': app.config['YEAR_PRICE'],
        'month_price_info': app.config['MONTH_PRICE_INFO'],
        'year_price_info': app.config['YEAR_PRICE_INFO'],
    }


@app.before_request
def before_request():
    from over.handlers.helper import random_str

    if not hasattr(g, 'user'):
        g.user = None
        user_id = session.get('user_id')
        if user_id:
            load_user(user_id)

    # 对于匿名访问,给予一个随机的值放在session中, 这样就可以在下单的时候
    # 通过这个与用户关联起来
    if not hasattr(g, 'user_visit'):
        if 'user_visit' not in session:
            user_visit = random_str()
        else:
            user_visit = session['user_visit']

        g.user_visit = user_visit

    g.time = time.time()


@app.after_request
def after_request(resp):
    g.delta = time.time() - g.time
    resp.headers['X-Process-Time'] = str(g.delta)
    return resp


@app.add_template_filter
def period(value):
    from over.model import Product
    if value == Product.PERIOD_MONTH:
        return u'月'
    if value == Product.PERIOD_YEAR:
        return u'年'
    if value == Product.PERIOD_DAY:
        return u'日'
    if value == Product.PERIOD_WEEK:
        return u'周'
    return u''


@app.add_template_filter
def order_status(value):
    d = {0: u"待支付", 1: u"支付中",
         2: u"支付完成", 3: u"支付超时",
         4: u"超时支付完成", 5: u"取消", 6: u"重新发起支付"}
    return d.get(value)


@app.add_template_filter
def email_name(value):
    return value.split('@')[0]


from .handlers import index
from .handlers import auth
from .handlers import my
from .handlers import qr

app.register_blueprint(index.mod)
app.register_blueprint(auth.mod, url_prefix='/auth')
app.register_blueprint(my.mod, url_prefix='/my')
app.register_blueprint(qr.mod, url_prefix='/qr')

print(app.url_map)

from . import mail as _mail